<template>
  <Layout :user="user" :on-logout="handleLogout">
    <div class="qr-verification-container">
    <div class="header">
      <h2>访客二维码验证</h2>
      <p>请将访客二维码对准扫描框进行验证</p>
    </div>
    
    <!-- 扫描区域 -->
    <div class="scan-section">
      <QRCodeScanner
        ref="scannerRef"
        :auto-start="true"
        :stop-on-success="true"
        @scanSuccess="handleScanSuccess"
        @scanError="handleScanError"
        @statusChange="handleStatusChange"
      />
    </div>
    
    <!-- 验证结果展示 -->
    <div v-if="verificationResult" class="result-section" :class="verificationResult.success ? 'success' : 'error'">
      <div class="result-header">
        <el-icon :size="28">
          <Check v-if="verificationResult.success" />
          <Close v-else />
        </el-icon>
        <h3>{{ verificationResult.title }}</h3>
      </div>
      
      <div v-if="verificationResult.success && visitorInfo" class="visitor-info">
        <div class="info-item">
          <label>访客姓名：</label>
          <span>{{ visitorInfo.name }}</span>
        </div>
        <div class="info-item">
          <label>身份证号：</label>
          <span>{{ visitorInfo.id_card }}</span>
        </div>
        <div class="info-item">
          <label>来访单位：</label>
          <span>{{ visitorInfo.company || '-' }}</span>
        </div>
        <div class="info-item">
          <label>访问事由：</label>
          <span>{{ visitorInfo.visit_reason }}</span>
        </div>
        <div class="info-item">
          <label>被访人员：</label>
          <span>{{ visitorInfo.interviewee }}</span>
        </div>
        <div class="info-item" v-if="visitorInfo.is_special">
          <label>特殊访客：</label>
          <span class="special-badge">是</span>
        </div>
      </div>
      
      <p class="result-message">{{ verificationResult.message }}</p>
      
      <div class="result-actions">
        <el-button 
          type="primary" 
          @click="resetVerification"
        >
          重新扫描
        </el-button>
        <el-button 
          v-if="verificationResult.success"
          @click="viewTodayRecords"
        >
          查看今日记录
        </el-button>
      </div>
    </div>
    
    <!-- 操作记录 -->
    <div v-if="recentOperations.length > 0" class="operations-log">
      <h4>最近操作记录</h4>
      <div class="operations-list">
        <div v-for="op in recentOperations"
:key="op.id"
class="operation-item"
:class="op.success ? 'success' : 'error'"
>
          <span class="op-time">{{ op.time }}</span>
          <span class="op-result">{{ op.result }}</span>
          <span class="op-visitor">{{ op.visitor || '未知访客' }}</span>
        </div>
      </div>
    </div>
      </div>
    </Layout>
  </template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import Layout from '../../components/common/Layout.vue'
import { useAuthStore } from '../../stores/auth'
import { Check, Close } from '@element-plus/icons-vue'
import QRCodeScanner from '../../components/verification/QRCodeScanner.vue'
import request from '../../utils/request'

// 类型定义
interface VisitorInfo {
  id: number;
  name: string;
  id_card?: string;
  company?: string;
  visit_reason?: string;
  interviewee?: string;
  is_special: boolean;
}

interface VerificationResult {
  success: boolean;
  title: string;
  message: string;
}

interface OperationLog {
  id: string;
  time: string;
  success: boolean;
  result: string;
  visitor: string;
}

// 使用auth store
const authStore = useAuthStore()
const router = useRouter()

// Layout组件需要的user props
const user = computed(() => ({
  name: authStore.userInfo?.name || '未知用户',
  role: authStore.userInfo?.role || 'guard',
  phone: authStore.userInfo?.phone || undefined,
  district: undefined // 根据实际情况设置
}))

// Layout组件需要的onLogout回调
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 组件引用和状态
const scannerRef = ref<InstanceType<typeof QRCodeScanner> | null>(null);
const verificationResult = ref<VerificationResult | null>(null);
const visitorInfo = ref<VisitorInfo | null>(null);
const recentOperations = ref<OperationLog[]>([]);
const isLoading = ref(false);

// 处理扫描成功
const handleScanSuccess = async (qrCodeData: string) => {
  if (isLoading.value) return;
  
  isLoading.value = true;
  
  try {
    // 调用后端验证API
    const response = await request.post('/api/qrcode/verify', {
      qr_code: qrCodeData
    });
    
    const data = response.data;
    
    // 解析验证结果
    verificationResult.value = {
      success: true,
      title: '验证成功',
      message: data.message || '访客二维码验证成功'
    };
    
    // 提取访客信息
    visitorInfo.value = {
      id: data.visitor_id,
      name: data.visitor_name,
      id_card: data.id_card || '', 
      company: data.company || '', 
      visit_reason: data.visit_reason || '', 
      interviewee: data.interviewee || '', 
      is_special: data.is_special || false 
    };
    
    // 添加到操作记录
    addOperationLog(true, '验证成功', data.visitor_name);
    
    ElMessage.success('二维码验证成功');
  } catch (error: any) {
    // 处理验证失败
    const errorMessage = error.message || '验证失败，请稍后重试';
    
    verificationResult.value = {
      success: false,
      title: '验证失败',
      message: errorMessage
    };
    
    // 添加到操作记录
    addOperationLog(false, errorMessage, '未知访客');
    
    ElMessage.error('二维码验证失败');
  } finally {
    isLoading.value = false;
  }
};

// 处理扫描错误
const handleScanError = (error: Error) => {
  ElMessage.warning(`扫描错误: ${error.message}`);
};

// 处理扫描器状态变化
const handleStatusChange = (active: boolean) => {
  if (active) {
    ElMessage.info('扫描器已启动');
  } else {
    ElMessage.info('扫描器已关闭');
  }
};

// 重置验证状态
const resetVerification = () => {
  verificationResult.value = null;
  visitorInfo.value = null;
  
  // 重新启动扫描器
  if (scannerRef.value) {
    // 这里可以通过组件的公共方法来控制扫描器
    // 由于我们在QRCodeScanner组件中没有暴露公共方法，所以这里只重置状态
    ElMessage.info('请重新扫描二维码');
  }
};

// 查看今日记录
const viewTodayRecords = () => {
  router.push('/guard/records');
};

// 添加操作记录
const addOperationLog = (success: boolean, result: string, visitor: string) => {
  const now = new Date();
  const timeString = now.toLocaleTimeString('zh-CN');
  
  const newLog: OperationLog = {
    id: Date.now().toString(),
    time: timeString,
    success,
    result,
    visitor
  };
  
  recentOperations.value.unshift(newLog);
  
  // 保留最近10条记录
  if (recentOperations.value.length > 10) {
    recentOperations.value = recentOperations.value.slice(0, 10);
  }
};

// 组件挂载时初始化
onMounted(() => {
  ElMessage.info('请将访客二维码对准扫描框进行验证');
});
</script>

<style scoped>
.qr-verification-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.header h2 {
  color: #303133;
  margin-bottom: 8px;
}

.header p {
  color: #606266;
  font-size: 14px;
}

.scan-section {
  margin-bottom: 30px;
}

.result-section {
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.result-section.success {
  background-color: #f0f9ff;
  border-left: 4px solid #1890ff;
}

.result-section.error {
  background-color: #fff2f0;
  border-left: 4px solid #ff4d4f;
}

.result-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.result-header .el-icon {
  margin-right: 10px;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
}

.result-section.success .result-header h3 {
  color: #1890ff;
}

.result-section.error .result-header h3 {
  color: #ff4d4f;
}

.visitor-info {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.special-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 12px;
}

.result-message {
  margin-bottom: 20px;
  color: #606266;
}

.result-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.operations-log {
  background-color: #fafafa;
  padding: 16px;
  border-radius: 4px;
}

.operations-log h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.operations-list {
  max-height: 200px;
  overflow-y: auto;
}

.operation-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
  font-size: 12px;
}

.operation-item:last-child {
  border-bottom: none;
}

.op-time {
  width: 80px;
  color: #909399;
}

.op-result {
  flex: 1;
  margin: 0 8px;
}

.operation-item.success .op-result {
  color: #67c23a;
}

.operation-item.error .op-result {
  color: #f56c6c;
}

.op-visitor {
  min-width: 80px;
  color: #606266;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 600px) {
  .qr-verification-container {
    padding: 10px;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .result-actions .el-button {
    width: 100%;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item label {
    width: auto;
    margin-bottom: 4px;
  }
}
</style>